package son.hut.vn.student.ad5;

import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import son.hut.vn.DecodePolyline;
import son.hut.vn.JSONParser;
import son.hut.vn.R;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;

public class DirectionStudent extends FragmentActivity{
	private GoogleMap googleMap;
	
	private DecodePolyline decodePolyline;
	private JSONParser jsonParser;
	private String url;
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.direction_student);
		
		googleMap =((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
		
		decodePolyline =  new DecodePolyline();
		jsonParser = new JSONParser();
		
		//fix cung dau vao
		url = decodePolyline.makeURL("Hanoi,Vietnam",  "Haiphong,Vietnam");
	}
	
	public void searchDirection(View view){
		String result = jsonParser.parserJson(url);
		
		if(result!=null){
			try {
				JSONObject jsonObject = new JSONObject(result);
				JSONArray jsonArray = jsonObject.getJSONArray("routes");
				JSONObject jsonObjectPolyline = jsonArray.getJSONObject(0);
				JSONObject jbOverviewPolyline = jsonObjectPolyline.getJSONObject("overview_polyline");
				String arrayPoints = jbOverviewPolyline.getString("points");
				
				//danh sach cac diem ma no di qua la
				List<LatLng> points = decodePolyline.decodePoly(arrayPoints);
				
				for (int i = 0; i < points.size()-1; i++) {
					LatLng source = points.get(i);
					LatLng des = points.get(i+1);
					
					//ve duong thang qua 2 diem nay
					googleMap.addPolyline(new PolylineOptions().add(source).add(des).color(Color.BLUE).width(3));
					googleMap.addMarker(new MarkerOptions()
					.position(source)
					.title("Ha noi").snippet("Kaha")
					.icon(BitmapDescriptorFactory.defaultMarker()));
					
				}
				
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		
	}
}
